import java.util.concurrent.TimeUnit;

/**
 * wait 和 sleep 释放锁行为的区别
 */
public class WaitSleepDemo {
    public static void main(String[] args) throws InterruptedException {
        Object lock = new Object();
        Object lock2 = new Object();
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                System.out.println("线程1：开始执行");
                try {
                    lock.wait(3 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程1：结束执行");
            }
        }, "wait");
        t1.start();

        Thread t2 = new Thread(() -> {
            synchronized (lock2) {
                System.out.println("线程2：开始执行");
                try {
                    Thread.sleep(3 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程2：结束执行");
            }
        }, "sleep");
        t2.start();

        // 创建 2 个线程，先让线程休眠 1s 之后，尝试获取，看能不能获取到锁
        // 如果可以获取到锁，说明休眠时线程是释放锁的，而如果获取不到锁，说明是不释放锁
        Thread t3 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("尝试获取 wait 方法的锁");
            synchronized (lock) {
                System.out.println("成功获取 wait 的锁");
            }
        }, "wait2");
        t3.start();

        Thread t4 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("尝试获取 sleep 方法的锁");
            synchronized (lock2) {
                System.out.println("成功获取 sleep 的锁");
            }
        }, "sleep2");
        t4.start();

    }
}